<template>
  <ECharts class="chart" :option="option" />
</template>

<script setup>
import ECharts from 'vue-echarts'
import { ref, computed, onMounted } from 'vue'
import { getCaseCauseList } from '@/api/flaud/caseCause'

const page = ref(0)
const total = ref(0)
const pageSize = ref(0)
const tableData = ref([])
const searchInfo = ref({})

onMounted(() => {
  getTableData()
})

const getTableData = async () => {
  const table = await getCaseCauseList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
    // 数据获取后，统计 causeType 数量并更新 mydata
    countCauseType()
  }
  console.log(tableData.value)
}

// 用于存储统计后的案由数据
const mydata = ref([])

// 统计 causeType 数量的函数
const countCauseType = () => {
  const countMap = {}
  tableData.value.forEach(item => {
    const causeType = item.causeType
    if (countMap[causeType]) {
      countMap[causeType]++
    } else {
      countMap[causeType] = 1
    }
  })
  // 将 countMap 转换为 ECharts 所需的数据格式
  mydata.value = Object.entries(countMap).map(([name, value]) => ({ name, value }))
}

const option = computed(() => ({
  title: {
    text: '案由比例',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '案由分布',
      type: 'pie',
      radius: '50%',
      data: mydata.value,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>